//引入axios
import axios from "axios";

//2.axios 创建对象
const request = axios.create({
    baseURL:'https://api.shop.eduwork.cn',
    timeout:8000,
})
const win:any = window;
request.interceptors.request.use((config)=>{
    //config接口配置信息
    //1.获取token
    let token = localStorage.getItem('token');
    //2.判断token是否存在
    if(token){
        //3.添加到请求头上
        config.headers.Authorization= `Bearer ${token}`;
    }

    return config;
},(error)=>{
    return Promise.reject(error);
})

request.interceptors.response.use((response)=>{
    return response.data;
},(error)=>{
    //
    const {response} = error;

    console.log('response',response);
    switch(response.status){
        case 401:
            win.$message.error('登陆失败，请重新登陆');
            localStorage.removeItem('token');
            setTimeout(()=>{
                window.location.href="/login"
            },500)
            break;
        case 404:
            win.$message.error('接口不存在')
            break;
        case 500:
        case 502:
            win.$message.error('网络异常')
            break;
        case 422:
        const msg = response.data.errors[Object.keys(response.data.errors)[0]][0];
        win.$message.error(msg);
            break;
    }



    return Promise.reject(error);
})

//抛出信息

export default request;